package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Company;
import model.DBUtil;
import model.Job;
import model.Puser;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/api/new-company-list.json")
public class 公司搜索 extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String keyword = req.getParameter("keyword");
        if(keyword != null&& keyword.trim().isEmpty()){
            keyword = null;
        }
        List<Company> companyList = new ArrayList<>();
        Object result;
        result = new Object(){
            public Object data = companyList;
        };
        try(Connection c = DBUtil.getConnection()){
            String sql;
            if(keyword==null) {
                sql = "SELECT * FROM company  ORDER BY ruid  DESC";
            }else {
                sql = "SELECT * FROM company WHERE gtitle LIKE ?  ORDER BY ruid  DESC";
            }
            try(PreparedStatement s = c.prepareStatement(sql)){
                if(keyword !=null){
                    s.setString(1,"%"+ keyword+ "%");
                }
                try (ResultSet rs = s.executeQuery()){
                    while(rs.next()){
                        Company company = new Company();
                        company.ruid = rs.getString("ruid");
                        company.cid = rs.getString("cid");
                        company.gtitle = rs.getString("gtitle");
                        company.gtype= rs.getString("gtype");
                        company.gsalary = rs.getString("gsalary");
                        company.gcontents = rs.getString("gcontents");
                        company.day = rs.getString("day");
                        companyList.add(company);
                    }
                }
            }
        } catch (SQLException exception) {
            exception.printStackTrace();
        }
        String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(result);
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        resp.getWriter().println(json);
    }
}
